package com.ruding.disruptor.service;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ruding.disruptor.config.ReportStatus;
import com.ruding.disruptor.init.SeriesData;
import com.ruding.disruptor.init.SeriesDataEventQueueHelper;
import com.ruding.disruptor.mapper.EvidenceRecordMapper;
import com.ruding.disruptor.model.EvidenceRecord;
import com.ruding.disruptor.utils.MapperProxy;
import com.ruding.disruptor.utils.http.DataSender;

@RestController
public class FilesServiceImpl {

	private static final Logger LOG = LoggerFactory.getLogger(FilesServiceImpl.class);
	@Autowired
	SeriesDataEventQueueHelper queueHelper;

	EvidenceRecordMapper mapper = MapperProxy.getMapper(EvidenceRecordMapper.class);

	@RequestMapping(value = "/scan")
	public void scanFileList(String strPath,String sendUrl){
		mapper.ensureTable();
		SeriesData<String> data = new SeriesData<>("scan", strPath, 1, sendUrl);
		queueHelper.tryPublishEvent(data);
	}

	public synchronized void  scanFileAndSend(EvidenceRecord record, long lastModified, List<String> filePaths, String url) {
		if(record != null){
			if(record.getLastModified() < lastModified || !record.isReported()) {
				mapper.updateStatus(filePaths, ReportStatus.PENDING.code());
			}
		}else{
			record = new EvidenceRecord();
			record.setFilePath(filePaths.get(0));
			record.setLastModified(lastModified);
			record.setStatus(ReportStatus.PENDING.code());
			record.setReportTime(-1L);
			mapper.saveEvidenceRecord(record);
		}
		List<EvidenceRecord> list = Arrays.asList(record);
		JSONObject json = new JSONObject();
		json.put("data", list);
		boolean success = DataSender.send(url,json);
		if(success) {
			mapper.updateStatus(filePaths, ReportStatus.REPORTED.code());
		}
	}
}
